package com.shyfu.controllers;

import com.shyfu.Utils;
import com.shyfu.entities.Book;
import com.shyfu.entities.Comment;
import com.shyfu.entities.User;
import com.shyfu.services.BookService;
import com.shyfu.services.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Date;

/**
 * Created by Svitlana on 04-Apr-14.
 */
@Controller
@RequestMapping("*/book")
public class BookPageController {

    @Autowired
    private BookService bookService;
    @Autowired
    private ControllerUtils controllerUtils;
    @Autowired
    private CommentService commentService;

    @RequestMapping("/{id}")
    public ModelAndView getBookView(@PathVariable("id") String id, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        User user = controllerUtils.getUser(request);
        System.out.println("BookPageController user=" + user);
        modelAndView.addObject("user", user);
        modelAndView.setViewName("book");
        Book book = bookService.getBook(Long.parseLong(id));
        modelAndView.addObject("book", book);
        modelAndView.addObject("contextPath", Utils.getContextPath(request));
        return modelAndView;
    }

    @RequestMapping(value = "/{id}/comment", method = RequestMethod.POST)
    public String addComment(@PathVariable("id") String id,
                             @RequestParam(value = "content") String content,
                             HttpServletRequest request) {
        User user = controllerUtils.getUser(request);
        Book book = bookService.getBook(Long.parseLong(id));
        Comment comment = new Comment();
        comment.setUser(user);
        comment.setBook(book);
        comment.setContent(content);
        Date date = new Date();
        comment.setCreated(new Timestamp(date.getTime()));
        commentService.addComment(comment);
        return "redirect:/librry/book/" + id;
    }
}